//获取权限方法
var userInfo = getAuthority();

var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};

    layui.use(['layer', 'form', 'table', 'util', 'dtree','admin','laypage','tree'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        var dtree = layui.dtree;
        var admin = layui.admin;
        var laypage = layui.laypage;
        var tree = layui.tree;

        var Authorization;//请求接口用
        var count = 0;//总个数
        var current=1;//当前页
        var groupName = '';//枚举分组名称
        var gid = '';//枚举id
        var vid = '';//版本值id
        var isClickRowTool = false;//是否是点击表格行工具条
        var IdentValueTree = [];//存放分组值树数据
        var IdentValueSelected = {};//分组值树选中节点

        if(userInfo){
            var access_token = localStorage.getExpire("access_token");
            var token_type = localStorage.getExpire("token_type");
            Authorization = token_type+" "+access_token;

            getIdentGroupPower();
            getIdentGroupTablePower();
            getIdentValuePower();

            getIdentGroupTableData();
        }

        var setting={//树设置
            identValueSetting:{//区划树设置
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false,
                    drag: {
                        isCopy: true,
                        isMove: false,
                        prev: false,
                        next: false,
                        inner: false
                    }
                },
                data: {
                    key: {
                        children: "sub",
                        isParent: "isParent",
                        title: "name"
                    },
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onExpand: onExpandIdentValueTree,
                    onClick: identValueOnClick
                },
                view: {
                    showIcon: true,
                    showLine: true
                }
            },
        }

        // 搜索按钮点击事件
        form.on('submit(formSubSearchGroup)', function (data) {
            groupName = data.field.groupName;
            getIdentGroupTableData();
        });

        // 打开新增分组弹窗
        $('#add-btn-ident-group').click(function () {
            showAddGroupModel();
        });

        // 表格工具条点击事件
        table.on('tool(identGroupTable)', function (obj) {
            isClickRowTool = true;
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'edit') { // 修改
                showGroupEditModel(data);
            } else if (layEvent === 'delete') { // 删除
                showGroupDeleteModel(data);
            }else if(layEvent === 'version'){//版本管理
                showVersionModel(data);
            }
        });

        //监听表格行单击事件
        table.on('row(identGroupTable)', function(obj){
            if(!isClickRowTool){
                obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');

                IdentValueSelected = {};
                $("#treeTbTree").empty();
                gid = obj.data.id;
                getVersionList(function (versionList) {
                    var obj = {
                        versionList:versionList
                    }
                    var str = template("version-tmpl",obj);
                    document.getElementById("version-tmpl-box").innerHTML = str;
                    form.render('select');

                    if(versionList.length>0){
                        vid = versionList[0].id;
                        getIdentRootValue();
                    }
                });
            }
        });

        form.on('select(versionSelect)', function(data){
            vid = data.value;
            getIdentRootValue();
        });

        $("#addIdentValueBtn").click(function () {
            openAddIdentValueModel(IdentValueSelected);
        });
        $("#editIdentValueBtn").click(function () {
            if(IdentValueSelected.hasOwnProperty("id")){
                openEditIdentValueModel(IdentValueSelected);
            }else{
                layer.msg("请先选中分组值节点", {icon: 2});
            }
        });

        $("#deleteIdentValueBtn").click(function () {
            if(IdentValueSelected.hasOwnProperty("id")){
                openDeleteIdentValueModel(IdentValueSelected);
            }else{
                layer.msg("请先选中分组值节点", {icon: 2});
            }
        });

        $("#importIdentValueBtn").click(function () {
            openImportIdentValueModel();
        });

        /*渲染分组权限*/
        function getIdentGroupPower() {
            var str = template("ident-group-tmpl",{});
            document.getElementById("ident-group-tmpl-box").innerHTML = str;
        }

        /*渲染分组表格里的权限*/
        function getIdentGroupTablePower() {
            var str = template("ident-group-tableHandle-tmp",{});
            document.getElementById("ident-group-tableHandle-box").innerHTML = str;
            // init();
        }

        /*渲染分组值权限*/
        function getIdentValuePower() {
            var str = template("ident-value-tmpl",{});
            document.getElementById("ident-value-tmpl-box").innerHTML = str;
        }

        /*获取数据分组表格数据*/
        function getIdentGroupTableData(){
            var req={
                current: current,
                size: pageSize,
                name:groupName
            };
            axios.get(microUrl.group.queryList,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        renderGroupTable(data);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

        /*渲染分组表格*/
        function renderGroupTable(data) {
            table.render({
                elem: '#identGroupTable',
                cellMinWidth: 100,
                page: false,
                size: 'sm', //小尺寸的表格
                data:data.records,
                cols: [[
                    {type:'numbers', title: '#'},
                    {field: 'name', align: 'center', title: '名称'},
                    {field: 'memo', align: 'center', title: '描述'},
                    {align: 'center', toolbar: '#ident-group-tableHandle-box', title: '操作', minWidth: 120}
                ]]
            });

            laypage.render({
                elem: 'page-box'
                ,count: data.total,
                limit:pageSize,
                groups:1,
                curr:current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        getIdentGroupTableData();
                    }
                }
            });
            var divbox = $("#identGroupTable").next(".layui-table-view");
            $(divbox).find("table tr").eq(1).click();
        }

        /*显示新增分组弹窗*/
        function showAddGroupModel() {
            admin.open({
                type: 1,
                title: '新增分组',
                offset: "auto",
                content: $('#model-add-Group').html(),
                success: function (layero, dIndex) {
                    // 表单提交事件
                    form.on('submit(addGroup)', function (data) {
                        layer.load(2);
                        var formData = new FormData();
                        formData.append('name',data.field.name);
                        formData.append('memo',data.field.memo);
                        formData.append('sort',data.field.sort);
                        axios({
                            method: 'POST',
                            url:microUrl.group.addGroup,
                            data:formData,
                            headers:{
                                'Authorization':Authorization
                            }
                        })
                            .then(function (response) {
                                if(response.status == 200 &&response.data.message == "success"){
                                    layer.close(dIndex);
                                    layer.closeAll('loading');
                                    layer.msg("新增成功", {icon: 1});
                                    getIdentGroupTableData();
                                }else{
                                    layer.closeAll('loading');
                                    layer.msg(response.data.message, { icon: 2 });
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                    // 进行重新登陆
                                    localStorage.clear();
                                    top.location.href=loginPageUrl;
                                }
                            });

                        return false;
                    });
                }
            });
        }

        /*显示编辑分组弹窗*/
        function showGroupEditModel(obj) {
                admin.open({
                    type: 1,
                    title: '编辑分组',
                    offset: "auto",
                    content: $('#model-edit-Group').html(),
                    success: function (layero, dIndex) {
                        // // 回显数据
                        form.val('editGroupForm', obj);
                        // 表单提交事件
                        form.on('submit(editGroup)', function (data) {
                            layer.load(2);
                            var formData = new FormData();
                            formData.append('id',obj.id);
                            formData.append('memo',data.field.memo)
                            formData.append('name',data.field.name)
                            formData.append('sort',obj.sort)
                            formData.append('status',obj.status)
                            formData.append('version',obj.version)
                            axios({
                                method: 'put',
                                url:microUrl.group.editGroup,
                                data:formData,
                                headers:{
                                    'Authorization':Authorization
                                }
                            })
                                .then(function (res) {
                                    if (res.status == 200&&res.data.message=="success") {
                                        layer.close(dIndex);
                                        layer.closeAll('loading');
                                        layer.msg("编辑成功", {icon: 1});
                                        getIdentGroupTableData();
                                    } else {
                                        layer.closeAll('loading');
                                        layer.msg(res.data.message, {icon: 2});
                                    }
                                })
                                .catch(function (error) {
                                    console.log(error);
                                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                        // 进行重新登陆
                                        localStorage.clear();
                                        top.location.href=loginPageUrl;
                                    }
                                })
                            return false;
                        });

                    },
                    end :function(){
                        isClickRowTool = false;
                    }
                });
        }
        /*显示删除分组弹窗*/
        function showGroupDeleteModel(obj) {
            layer.confirm('确认删除吗？', {
                skin: 'layui-layer-admin',
                size:'sm',
                shade: .1,
                cancel: function(index, layero){//取消操作，点击右上角的X
                    isClickRowTool = false;
                }
        }, function (i,dIndex) {//确定
                layer.close(i);
                layer.load(2);
                axios({
                    method: 'delete',
                    url:microUrl.group.deleteGroup+obj.id,
                    headers:{
                        'Authorization':Authorization
                    }
                })
                    .then(function (res) {
                        if (res.status == 200&&res.data.message=="success") {
                            layer.closeAll('loading');
                            layer.msg("删除成功", {icon: 1});
                            getIdentGroupTableData();
                        } else {
                            layer.closeAll('loading');
                            layer.msg(res.data.message, {icon: 2});
                        }
                        isClickRowTool = false;
                    })
                    .catch(function (error) {
                        console.log(error);
                        if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                            // 进行重新登陆
                            localStorage.clear();
                            top.location.href=loginPageUrl;
                        }
                    })
            },function () {//取消
                isClickRowTool = false;
            });
        }

        /*显示版本管理弹窗*/
        function showVersionModel(obj) {
            var str = template("ident-group-versiontableHandle-tmp",{});
            document.getElementById("ident-group-version-tableHandle-box").innerHTML = str;

            admin.open({
                type: 1,
                title: '版本管理',
                offset: "auto",
                area: '745px',
                content: $('#mode-version-Group').html(),
                success: function (layero, dIndex) {
                    gid = obj.id;
                    getVersionList(function(versionList){
                        renderVersionList(versionList);
                    });

                    // 添加版本表单提交事件
                    form.on('submit(addVersion)', function (data) {
                        var formData = new FormData();
                        formData.append('gid',gid);
                        formData.append('memo',data.field.memo);
                        formData.append('value_version',data.field.value_version);

                        axios({
                            method: 'POST',
                            url:microUrl.version.addVersion,
                            data:formData,
                            headers:{
                                'Authorization':Authorization
                            }
                        })
                            .then(function (response) {
                                if(response.status == 200 &&response.data.message == "success"){
                                    layer.closeAll('loading');
                                    layer.msg("添加成功", {icon: 1});
                                    getVersionList(function (versionList) {
                                        renderVersionList(versionList);
                                    });
                                    isClickRowTool = false;
                                }else{
                                    layer.closeAll('loading');
                                    layer.msg(response.data.message, { icon: 2 });
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                    // 进行重新登陆
                                    localStorage.clear();
                                    top.location.href=loginPageUrl;
                                }
                            });

                        return false;
                    });

                    // 表格工具条点击事件
                    table.on('tool(identGroupVersionTable)', function (obj) {
                        var data = obj.data;
                        var layEvent = obj.event;
                        if (layEvent === 'delete') { // 删除
                            deleteVersion(data);
                        }
                    });
                },
                end: function () {//重新渲染版本下拉框，防止版本已经被更改过
                    isClickRowTool = false;
                    getVersionList(function (versionList) {
                        versionArr = versionList;
                        if(versionList.length>0){
                            var obj = {
                                versionList:versionList
                            }
                            var str = template("version-tmpl",obj);
                            document.getElementById("version-tmpl-box").innerHTML = str;
                            form.render('select');
                            vid = versionList[0].id;
                            getIdentRootValue();
                        }else{
                            $("#treeTbTree").empty();
                            $("#version-tmpl-box").empty();
                            form.render('select');
                        }
                    });
                }

            });

        }
        /*获取版本列表*/
        function getVersionList(callback) {
            var req={
                gid : gid
            };
            var url = microUrl.version.queryVersion+gid;
            axios.get(url,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        callback(data);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

        /*渲染版本列表*/
        function renderVersionList(versionList) {
            // 渲染表格
            table.render({
                elem: '#identGroupVersionTable',
                size: 'sm', //小尺寸的表格
                skin:'nob',
                data:versionList,
                page: false,
                cellMinWidth: 100,
                cols: [[
                    {type:'numbers', title: '#'},
                    {field: 'value', align: 'center', title: '值'},
                    {field: 'memo', align: 'center', title: '备注'},
                    {align: 'center', toolbar: '#ident-group-version-tableHandle-box', title: '操作', minWidth: 120}
                ]]
            });
        }
        /*删除版本*/
        function deleteVersion(obj){
            layer.confirm('确认删除吗？', {
                skin: 'layui-layer-admin',
                size:'sm',
                shade: .1,
            }, function (i,dIndex) {//确定
                layer.close(i);
                layer.load(2);
                axios({
                    method: 'delete',
                    url:microUrl.version.deleteVersion+obj.id,
                    headers:{
                        'Authorization':Authorization
                    }
                })
                    .then(function (res) {
                        if (res.status == 200&&res.data.message=="success") {
                            layer.closeAll('loading');
                            layer.msg("删除成功", {icon: 1});
                            getVersionList(function (versionList) {
                                var obj = {
                                    versionList:versionList
                                }
                                var str = template("version-tmpl",obj);
                                document.getElementById("version-tmpl-box").innerHTML = str;
                                form.render('select');
                                renderVersionList(versionList);
                            });
                        } else {
                            layer.msg(res.data.message, {icon: 2});
                            layer.closeAll('loading');
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                            // 进行重新登陆
                            localStorage.clear();
                            top.location.href=loginPageUrl;
                        }
                    })
            });
        }
        /*获取分组值根目录*/
        function getIdentRootValue(){
                getIdentValue('root',function (resArr) {
                    $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
            });
        }
        /*获取分组值*/
        function getIdentValue(parent_code ,callback) {
            var req={
                gid : gid,
                parent_code:parent_code ,
                vid:vid
            };
            var url = microUrl.identValue.queryEnum;
            axios.get(url,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        var resArr = [];
                        zhuanHuanTree(data,resArr);
                        // IdentValueTree = resArr;
                        callback(resArr)
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

        //查询下方区划树的下级区划值（懒加载）
        function onExpandIdentValueTree(event, treeId, treeNode) {
            if(treeNode.sub.length>0||treeNode.hasChild==0){
                return false;
            }else{
                getIdentValue(treeNode.code,function (resArr) {
                    const treeObj = $.fn.zTree.getZTreeObj("treeTbTree");
                    treeObj.addNodes(treeNode, resArr);
                });
            }

        }

        //转换菜单集合数据
        function zhuanHuanTree(tdata,resData) {
            if(Array.isArray(tdata) && tdata.length>0){
                tdata.forEach(function(v,i){
                    var newValue=v.name;
                    resData[i]=v;
                    resData[i].title=newValue;
                    resData[i].icon = "";
                    resData[i].isParent = "true";
                    resData[i].sub = [];
                });
            }
        }

        //选中分组值
        function identValueOnClick(event, treeId, treeNode){
            IdentValueSelected = treeNode;
        }

        /*打开新增分组值弹窗*/
        function openAddIdentValueModel(IdentValueSelected) {
            window.IdentValueSelected = IdentValueSelected;  // 传递数据到表单页面，也可以使用top.xxx
            window.IdentGroupData = {
                gid:gid,
                vid:vid
            }
            window.addIdentValueFormIsOk = false;  // 重置表单操作成功标识，也可以使用top.xxx

                admin.open({
                    title: '新增分组值',
                    url: 'ident/addIdentValue.html',
                    end: function () {
                        if (window.addIdentValueFormIsOk) {  // 判断表单操作成功标识，也可以使用top.xxx
                            getIdentRootValue();
                        }
                    },
                    success: function (layero, dIndex) {
                        // 弹窗超出范围不出现滚动条
                        $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    }
                });

        }
        /*打开编辑分组值弹窗*/
        function openEditIdentValueModel(IdentValueSelected) {
            window.IdentValueSelected = IdentValueSelected;  // 传递数据到表单页面，也可以使用top.xxx
            window.editIdentValueFormIsOk = false;  // 重置表单操作成功标识，也可以使用top.xxx

                admin.open({
                    title: '编辑分组值',
                    url: 'ident/editIdentValue.html',
                    end: function () {
                        if (window.editIdentValueFormIsOk) {  // 判断表单操作成功标识，也可以使用top.xxx
                            getIdentRootValue();
                        }
                    },
                    success: function (layero, dIndex) {
                        // 弹窗超出范围不出现滚动条
                        $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    }
                });
        }
        /*打开删除分组值弹窗*/
        function openDeleteIdentValueModel(obj) {
            layer.confirm('确认删除吗？', {
                skin: 'layui-layer-admin',
                size:'sm',
                shade: .1
            }, function (index) {
                layer.close(index);
                layer.load(2);
                axios({
                    method: 'delete',
                    url:microUrl.identValue.deleteEnum+obj.id,
                    headers:{
                        'Authorization':Authorization
                    }
                })
                    .then(function (res) {
                        if (res.status == 200&&res.data.message=="success") {
                            layer.closeAll('loading');
                            layer.msg("删除成功", {icon: 1});
                            getIdentRootValue();
                        } else {
                            layer.closeAll('loading');
                            layer.msg(res.data.message, {icon: 2});
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                            // 进行重新登陆
                            localStorage.clear();
                            top.location.href=loginPageUrl;
                        }
                    })
            });
        }
        /*打开导入分组值弹窗*/
        function openImportIdentValueModel() {
            window.importIdentValueIsOk = false;
            window.Ident_selectedInfo = {
                gid:gid,
                vid:vid
            };
            admin.open({
                title: '导入分组值',
                url: 'ident/importIdentValue.html',
                end: function () {
                    if(window.importIdentValueIsOk){
                        getIdentRootValue();
                    }
                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        }
    });

